package com.alawn.security.config.filter;

import com.alawn.framework.core.component.CaptchaService;
import com.alawn.security.exception.CaptchaErrorException;
import lombok.Setter;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

@Setter
public class CaptchaValidateFilter extends AccessControlFilter {

    private boolean captchaEbabled = true;// 是否开启验证码支持

    private String captchaParam = "captcha";// 前台提交的验证码参数名

    private String failureKeyAttribute = "shiroLoginFailure"; // 验证码验证失败后存储到的属性名

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception {
        // 1、设置验证码是否开启属性，页面可以根据该属性来决定是否显示验证码
        request.setAttribute("captchaEbabled", captchaEbabled);

        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        // 2、判断验证码是否禁用 或不是表单提交（允许访问）
        if (captchaEbabled == false || !"post".equalsIgnoreCase(httpServletRequest.getMethod())) {
            return true;
        }
        // 3、此时是表单提交，验证验证码是否正确
        return CaptchaService.validateCaptcha(httpServletRequest, httpServletRequest.getParameter(captchaParam));
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        request.setAttribute(failureKeyAttribute, CaptchaErrorException.class.getName());
        return true;
    }

}
